<script setup lang='ts'>
  import { nextTick, reactive, ref, computed } from 'vue';
  import { gamesApi } from '@/api/controller';
  import { ToastSuccess, ToastWarning, Toastloading, allNumber } from '@/utils/public';
  import serachGift from '@/components/serachGift/index.vue';
  import serachGoods from '@/components/serachGoods/index.vue';
  const formLabelWidth = '120px'
  const dataForm = ref(),
  rewardDataForm = ref()
  const $emit = defineEmits(['updateList'])
  const action = reactive({
    dialogFormVisible:false,
    dialogRewardFormVisible:false,
    disabled:false,
    title:'',
    numTableName:'',
    serachType:0,
    rewardIndex:0,
    serachGoodsType:0,
    awardList:[] as Array<any>,
    isRoundType:[] as Array<any>,
    rewardType:[] as Array<any>,
    isSenderType:[] as Array<any>,
    rewardFormType:0,
  })
  const rewardTypeChange = (type:number = 0)=>{
    let text = '奖励数量'
    if([1,2,4,5,8].indexOf(type) > -1) {
      text = '奖励天数'
      action.serachType = 1
      // key 奖励类型参数 type商品类型
      action.serachGoodsType = [
        {key:1,type:1},
        {key:2,type:7},
        {key:4,type:3},
        {key:5,type:2},
        {key:8,type:11},
      ].find(res=>res.key == type)?.type || 0
    } else if(type == 3) {
      action.serachType = 2
    } else {
      action.serachType = 0
    }
    rewardForm.goods_id = ''
    rewardForm.goods_num = ''
    rewardFormRules.goods_num[0].message = `请输入${text}`
    action.numTableName = text
  }
  interface formQuert {
    id:number
    b_award_id:number
    level:number
    is_round:number
    award_json:string
  }
  interface rewardQuert {
    is_sender:number
    send_type:number
    goods_id:number | string
    goods_num:number | string
  }
  let form = reactive({} as formQuert),
  rewardForm = reactive({} as rewardQuert)
  const formRules = {
    level: [{ required: true, message: "请输入奖励楼层", trigger: "blur" }],
    is_round: [{ required: true, message: "请选择是否循环楼层", trigger: "blur" }],
    award_json: [{ required: true, message: "请填写奖励信息", trigger: "blur" }],
  },
  rewardFormRules = {
    is_sender: [{ required: true, message: "请选择奖励方", trigger: "blur" }],
    send_type: [{ required: true, message: "请选择奖励类型", trigger: "blur" }],
    goods_id: [{ required: true, message: "请选择奖励", trigger: "blur" }],
    goods_num: [{ required: true, message: `请输入奖励天数/奖励数量`, trigger: "blur" }],
  }
  const handleForm = (scoped:any={})=>{
    const { row={}, $index=-1 } = scoped
    const { is_sender='', send_type='', goods_id='', goods_num='' } = row
    if(send_type==7) {
      action.rewardFormType = goods_num > 0 ? 1 : 0
    } else {
      action.rewardFormType = goods_id?1:0
    }
    if(send_type) rewardTypeChange(send_type)
    action.rewardIndex = $index
    Object.assign(rewardForm,{
      is_sender,
      send_type,
      goods_id,
      goods_num
    })
    action.dialogRewardFormVisible = true
  }
  const handleSubmit = ()=>{
    dataForm.value.validate(async(valid:any)=>{
      if(!valid) return
      const loading = Toastloading()
      let submitSet = false
      const { b_award_id } = form
      form.award_json = JSON.stringify(action.awardList)
      if(b_award_id) {
        await gamesApi.customBridgeAwardEdit(form).then(()=>{
          ToastSuccess('编辑成功')
          submitSet = true
        }).catch(()=>{
          loading.close()
        })
      }
      else {
        await gamesApi.customBridgeAwardAdd(form).then(()=>{
          ToastSuccess('新增成功')
          submitSet = true
        }).catch(()=>{
          loading.close()
        })
      }
      if(submitSet) {
        loading.close()
        $emit('updateList')
        closeDialog()
      }
    })
  }
  const handleRewardSubmit = ()=>{
    rewardDataForm.value.validate(async(valid:any)=>{
      if(!valid) return
      if(!action.rewardFormType) action.awardList.push({...rewardForm})
      if(action.rewardFormType == 1) {
        action.awardList[action.rewardIndex] = {...rewardForm}
      }
      closeRewardDialog()
    })
  }
  const openDialog = async(query:any={})=> {
    const {
      id=0, b_award_id=0, level='', is_round='', award_json='',
      isRoundType=[], rewardType=[], isSenderType=[]
    } = query
    if(!id && !b_award_id) return ToastWarning('缺少盖楼配置ID或奖励ID')
    if(award_json) {
      action.awardList = JSON.parse(award_json)
    } else {
      action.awardList = []
    }
    const obj = {
      level, is_round
    } as any
    if(id) obj['id'] = id
    if(b_award_id) obj['b_award_id'] = b_award_id
    action.isRoundType = isRoundType
    action.rewardType = rewardType
    action.isSenderType = isSenderType
    Object.assign(form,obj)
    action.dialogFormVisible = true
    action.title = id?'创建楼层奖励':`编辑楼层：${level}奖励`
  }
  const closeDialog = ()=>{
    form = reactive({} as formQuert)
    nextTick(() => {
      dataForm.value.clearValidate();
    });
    action.dialogFormVisible = false
  }
  const closeRewardDialog = ()=>{
    rewardForm = reactive({} as rewardQuert)
    nextTick(() => {
      rewardDataForm.value.clearValidate();
    });
    action.dialogRewardFormVisible = false
  }
  defineExpose({
    openDialog
  })
</script>

<template>
  <div>
    <el-dialog
      top="10vh"
      class="xm-dialog input-width"
      v-model="action.dialogFormVisible"
      :close-on-click-modal="action.disabled"
      :show-close="action.disabled"
      :close-on-press-escape="action.disabled"
      width="50%"
      :title="action.title">
      <el-form ref="dataForm" :model="form" :rules="formRules">
        <el-form-item :label-width="formLabelWidth" label="是否循环楼层" prop="level">
          <el-select v-model="form.is_round" placeholder="请选择是否循环楼层">
            <el-option
              v-for="item in action.isRoundType"
              :key="item.type"
              :label="item.label"
              :value="item.type"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="奖励楼层" prop="level">
          <el-input
            :disabled="action.disabled"
            v-model="form.level"
            placeholder="请输入奖励楼层"
            @input="allNumber(form,'level')"
          />
        </el-form-item>
      </el-form>
      <el-button class="xm-mrAuto xm-mb10" type="primary" @click="handleForm()">新增奖励</el-button>
      <el-table
        class="xm-TableCenter"
        :data="action.awardList"
        border
      >
        <el-table-column min-width="120" prop="is_sender" label="奖励方">
          <template #default="scoped">
            {{ action.isSenderType.find(res=>res.type == scoped.row.is_sender)?.label || scoped.row.is_sender }}
          </template>
        </el-table-column>
        <el-table-column min-width="120" prop="send_type" label="奖励类型">
          <template #default="scoped">
            {{ action.rewardType.find(res=>res.type == scoped.row.send_type)?.label || scoped.row.send_type }}
          </template>
        </el-table-column>
        <el-table-column min-width="80" prop="goods_id" label="礼物/商品ID" />
        <el-table-column min-width="80" prop="goods_num" label="奖励数量/天数" />
        <el-table-column width="120"  label="操作">
          <template #default="scoped">
            <el-button type="primary" @click="handleForm(scoped)">编辑奖励</el-button>
          </template>
        </el-table-column>
      </el-table>
      <template v-if="!action.disabled" #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog
      top="10vh"
      class="xm-dialog input-width"
      v-model="action.dialogRewardFormVisible"
      :close-on-click-modal="action.disabled"
      :show-close="action.disabled"
      :close-on-press-escape="action.disabled"
      width="40%"
      :title="action.title">
      <el-form ref="rewardDataForm" :model="rewardForm" :rules="rewardFormRules">
        <el-form-item :label-width="formLabelWidth" label="奖励方" prop="is_sender">
          <el-select v-model="rewardForm.is_sender" placeholder="请选择奖励方">
            <el-option
              v-for="item in action.isSenderType"
              :key="item.type"
              :label="item.label"
              :value="item.type"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="奖励类型" prop="send_type">
          <el-select v-model="rewardForm.send_type" @change="rewardTypeChange" placeholder="请选择奖励类型">
            <el-option
              v-for="item in action.rewardType"
              :key="item.type"
              :label="item.label"
              :value="item.type"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="action.serachType == 1" :label-width="formLabelWidth" label="商品" prop="goods_id">
          <serachGoods
            version="0.0.1"
            :show_goods_type="[action.serachGoodsType]"
            v-model:goods_id="rewardForm.goods_id"
            v-model:goods_type="action.serachGoodsType" />
        </el-form-item>
        <el-form-item v-if="action.serachType == 2" :label-width="formLabelWidth" label="礼物" prop="goods_id">
          <serachGift
            version="0.0.1"
            :show_gift_type="[1]"
            v-model:gift_id="rewardForm.goods_id" />
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" :label="action.numTableName" prop="goods_num">
          <el-input
            v-model="rewardForm.goods_num"
            :placeholder="`请输入${action.numTableName}`"
            @input="allNumber(rewardForm,'goods_num')"
          />
        </el-form-item>
      </el-form>
      <template v-if="!action.disabled" #footer>
        <span class="dialog-footer">
          <el-button @click="closeRewardDialog">取 消</el-button>
          <el-button type="primary" @click="handleRewardSubmit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>